var editor;
var sqlBackEditor;
$(function() {
	$("#userNameDiv").hide();
	$("#sqlFileBlock").hide();
	if ($("#sqlUploadType option:selected").val() == 'text') {
		$("#sqlFileBlock").hide();
	}
	if ($("#sqlUploadType option:selected").val() == 'file') {
		$("#sqlFileBlock").show();
	}
	$("#blockServeiceIPAddr").change(function() {
		if ($("#sqlUploadType option:selected").val() == 'text') {
			$("#sqlFileBlock").hide();
		}
		if ($("#sqlUploadType option:selected").val() == 'file') {
			$("#sqlFileBlock").show();
		}
	});
	
	$("#selectSqlTypeDiv").change(function(){
		if($("#sqlType option:selected").val() == 'e sql'){
			$("#userNameDiv").show();
		}else{
			$("#userNameDiv").hide();
		}
	});
	var paramJson = {};
	$(document).on("blur",".form-group",function(){
		paramJson['sqlType'] = $("#sqlType option:selected").val();
		paramJson['uploadType'] = $("#sqlUploadType option:selected").val();
		paramJson['project'] = $("#projectSelected option:selected").val();
		paramJson['dbName'] = $("#databaseName option:selected").attr("dbname");
		paramJson['dbType'] = $("#databaseName option:selected").attr("dbtype");
		paramJson['sqlTextEditor'] = editor.getValue();
		paramJson['sqlBackupEditor'] = sqlBackEditor.getValue();
		paramJson['userName'] = $("#userName").val();
	});
	var adIds = "";
	$("#databaseName").change(function (){
		adIds += $("#databaseName option:selected").val() + ",";
		paramJson['adId'] = adIds;
	});

	
	$("#sql-upload-form").ajaxForm({
		url : getRoot() + '/sqlupload/insertSqlUploadPost',
		beforeSubmit : function() {
			var sqlTEr = editor.getValue();
			$("#sqlText").val(sqlTEr);
			if ($("#databaseName").val() == '0') {
				swal("警告", "请选择数据库或者添加数据库", "warning");
				return false;
			}
			var email = $("#email").val();
			if (!$("#email").val()) {
				swal("警告", "部门负责人邮箱不能为空", "warning");
				return false;
			}
			var emailReg = new RegExp(LTS.ReExp.email);
			var emailArray = email.split(',');
			for(var i in emailArray){
				var em = emailArray[i];
				if (!emailReg.test($.trim(em))) {
					swal("警告", "部门负责人邮箱格式不正确，正确格式为：xxx@gomeplus.com", "warning");
					return false;
				}
			}
			if ($("#sqlUploadType option:selected").val() == 'file') {
				if (!$("#sqlFile1").val()) {
					swal("警告", "请上传文件，否则选择文本模式上传", "warning");
					return false;
				}
			}else{
				if (!$.trim($("#sqlText").val())) {
					swal("警告", "请填写SQL文本", "warning");
					return false;
				}
			}
			if (!$("#sqlUsage").val()) {
				swal("警告", "请填写SQL使用说明", "warning");
				return false;
			}
			if($("#sqlType option:selected").val() == 'e sql'){
				var userName = $("#userName").val();
				if(isEmpty(userName)){
					swal("警告","申请人不能为空","warning");
			        return false;
				}
				var ZN_NameReg = new RegExp(LTS.ReExp.ZnName);
				var result = userName.match(ZN_NameReg);
				if(null==result || 0==result.length){
					swal("警告","请输入中文姓名","warning");
			        return false;
				}
			}
		},
		data : paramJson,
		dataType : 'json',
		type : 'POST',
		resetForm : false,
		success : function(data) {
			if (data.success) {
				swal("成功", data.root, "success");
				return true;
			}
			if (!data.failure) {
				swal("失败", data.root, "error");
				return false;
			}
		}
	});
	
	//codemirror
	codemirrorSqlHint();
	
});

/**
 * CodeMirror代码高亮
 * */
function codemirrorSqlHint(){
	editor = CodeMirror.fromTextArea(document.getElementById('sqlText'), {
	    mode: "text/x-mysql",
	    indentWithTabs: true,
	    smartIndent: true,
	    lineNumbers: true,
	    matchBrackets : true,
	    autofocus: true,
	    extraKeys: {"Ctrl-Space": "autocomplete"},
	    hintOptions: {tables: {
	      users: {name: null, score: null, birthDate: null},
	      countries: {name: null, population: null, size: null}
	    }}
	  });
	editor.on("change",function(){
		editor.showHint();
	});
	sqlBackEditor = CodeMirror.fromTextArea(document.getElementById('sqlBackup'), {
	    mode: "text/x-mysql",
	    indentWithTabs: true,
	    smartIndent: true,
	    lineNumbers: true,
	    matchBrackets : true,
	    autofocus: true,
	    extraKeys: {"Ctrl-Space": "autocomplete"},
	    hintOptions: {tables: {
	      users: {name: null, score: null, birthDate: null},
	      countries: {name: null, population: null, size: null}
	    }}
	  });
	sqlBackEditor.on("change",function(){
		sqlBackEditor.showHint();
	});
}

var fileNum = 0;
var count = 1;
function addFile(){
	if(fileNum > 0){
		return false;
	}
	var fragment=document.createDocumentFragment();
	var divNode=document.getElementById("container");
	 
	var newDiv=document.createElement("div");
	newDiv.setAttribute("id","file"+count);
	fragment.appendChild(newDiv);
	 
	var newInput=document.createElement("input");
	newInput.setAttribute("type","file");
	newInput.setAttribute("name","选择文件");
	newDiv.appendChild(newInput);
	 
	var newInput=document.createElement("input");
	newInput.setAttribute("type","button");
	newInput.setAttribute("value","删除");
	newInput.setAttribute("onclick","delFile("+count+")");
	newInput.setAttribute("id","1");
	newDiv.appendChild(newInput);
	 
	divNode.appendChild(fragment);
	fileNum++;
	count++;
}
function delFile(num){
	fileNum--;
	if(fileNum < 0){
		fileNum = 0;
		return false;
	}
	$("#file"+num).remove();
}